﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.IO;

namespace DS_Server
{
    class ClientHandler
    {
        string dbPath = @"Data Source=AMIGO-UA\SQLEXPRESS;Initial Catalog=test;Integrated Security=True";
        string csvPath = "test.csv";
        string csvFilled = "tmp_filled.csv";
        
        public ClientHandler(HttpListenerContext context)
        {
            this.myContext = context;
            path = csvPath;
            Thread thr = new Thread(connect);
            thr.Start();
        }
        
        public HttpListenerContext myContext = null;
        public string message = "";
        string OutMessage = null;
        string DataFromClient = null;

        
        public void connect()
        {
            HttpListenerRequest request = myContext.Request;
            HttpListenerResponse response = myContext.Response;

            string method = request.HttpMethod;
            switch (method)
            {
                case "GET":
                    OutMessage = GetRequest();
                    break;
                case "POST":
                    OutMessage = PostRequest();
                    break;
                default:
                    break;
            }
            StreamWriter streamWriter = new StreamWriter(response.OutputStream);
            streamWriter.Write(OutMessage);
            streamWriter.Close();
        }
        ///        
        private string GetRequest()
        {
            HttpListenerRequest Request = this.myContext.Request;
            HttpListenerResponse Response = this.myContext.Response;
            StreamReader StreamReader = new StreamReader(Request.InputStream);
            DataFromClient = StreamReader.ReadToEnd();
            StreamReader.Close();
            Console.Write(Request);
            string FilePath = @"index2.html";
            string ContentType = "text/html";

            FileStream FS = null;
            try
            {
                FS = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
            catch (Exception ex)
            {
            }
            Response.ContentType = ContentType;
            Response.ContentLength64 = FS.Length;
            byte[] bytes = new byte[FS.Length];
            FS.Read(bytes, 0, Convert.ToInt32(FS.Length));
            string msgback = Encoding.ASCII.GetString(bytes);
            FS.Close();
            return msgback;

        }

        private string PostRequest()
        {
            HttpListenerRequest Request = this.myContext.Request;
            StreamReader streamReader = new StreamReader(Request.InputStream);
            DataFromClient = streamReader.ReadToEnd();
            streamReader.Close();

            action(DataFromClient);
            string msgback = messageToClient;
            return msgback;
        }
        /// <summary>
        /// 
        /// </summary>
        string messageToClient = null;
        string path = null;

        void action(string message)
        {            
            pList x = new pList();

            string[] strArray = message.Split(':', ';');
            int i = 0;
            try
            {
                switch (strArray[i])
                {
                    case "create":
                        Person p = new Person(Convert.ToInt32(strArray[i + 1]), strArray[i + 2], strArray[i + 3], Convert.ToInt32(strArray[i + 4]));
                        x.Add(p);

                        x.Create(path, (x[0] as Person));
                        messageToClient = "Created";
                        break;
                    case "read":
                        x.Read(path);

                        messageToClient = "list;";
                        foreach (Person pp in x)
                        {
                            messageToClient += pp.SaveToSCV();
                        }
                        break;
                    case "update":
                        x.Update(path, Convert.ToInt32(strArray[i + 1]), strArray[i + 2], strArray[i + 3], Convert.ToInt32(strArray[i + 4]));
                        messageToClient = "Updated";
                        break;
                    case "delete":
                        x.Delete(path, Convert.ToInt32(strArray[i + 1]));
                        messageToClient = "Deleted";
                        break;
                    default:
                        messageToClient = "unknown command!";
                        break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        /*
        void sendAnswer(string answerMessage)
        {
            string host = System.Net.Dns.GetHostName();
            IPAddress ipAddr = Dns.GetHostByName(host).AddressList[0];

            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 5051);
            Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sender.Connect(ipEndPoint);
            byte[] msg = Encoding.ASCII.GetBytes(answerMessage);
            sender.Send(msg);
            sender.Close();
        }*/
    }
}
